package com.xli.mybatis.plugin;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

@Slf4j
public class SqlExecutionTimePlugin implements InnerInterceptor {

    private final long thresholdMs = 1;

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        long startTime = System.nanoTime();
        // 执行原始查询逻辑
        InnerInterceptor.super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        long endTime = System.nanoTime();
        // 计算 SQL 执行时长
        long duration = TimeUnit.NANOSECONDS.toMillis(endTime - startTime);

        if (duration > thresholdMs) {
            // 打印日志
            String sqlId = ms.getId();
            log.info("SQL [{}] executed in {} ms", sqlId, duration);
        }
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        long startTime = System.nanoTime();
        // 执行原始更新逻辑
        InnerInterceptor.super.beforeUpdate(executor, ms, parameter);
        long endTime = System.nanoTime();
        // 计算 SQL 执行时长
        long duration = TimeUnit.NANOSECONDS.toMillis(endTime - startTime);

        if (duration > thresholdMs) {
            // 打印日志
            String sqlId = ms.getId();
            log.info("SQL [{}] executed in {} ms", sqlId, duration);
        }
    }
}
